package cn.doitedu.datayiee.rest.service;

import cn.doitedu.datayiee.rest.dao.KylinGroupByDao;
import cn.doitedu.datayiee.rest.pojo.AggExpr;
import cn.doitedu.datayiee.rest.pojo.GroupByBean;
import cn.doitedu.datayiee.rest.pojo.GroupByResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GroupByQueryServiceImpl implements GroupByQueryService {

    @Autowired
    KylinGroupByDao kylinGroupByDao;


    @Override
    public List<GroupByResultBean> groupByQuery(GroupByBean groupByBean) {
        String tableName = groupByBean.getTableName();
        List<String> dimCols = groupByBean.getDimCols();
        List<AggExpr> exprs = groupByBean.getExprs();

        StringBuilder sb1 = new StringBuilder();

        // 拼接 select后面的列
        for (String dimCol : dimCols) {
            // province,city,region,
            sb1.append(dimCol).append(",");
        }
        String columns = sb1.substring(0,sb1.length()-1);

        // 拼接维度列后面的聚合表达式
        StringBuilder sb2 = new StringBuilder();
        for (AggExpr expr : exprs) {
            // sum(pv_cnt),count(session_id),
            sb2.append(expr.getExpr()+"("+expr.getCol()+"),");
        }
        String aggExprs = sb2.substring(0,sb2.length()-1);

        String sql = "select " + columns + "," + aggExprs +" from " + tableName + " group by " + columns;

        List<GroupByResultBean> beans = kylinGroupByDao.queryGroupBy(sql);


        return beans;
    }
}
